package com.xqls.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtil {
    private static String RESOURCE ="sqlMapConfig.xml";
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

   public static void initSqlFactor(){
        try {
            InputStream inputStream = Resources.getResourceAsStream(RESOURCE);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

    public static SqlSessionFactory getSqlsessionFactory(){
        return factory;
    }

    public static void close(){
        SqlSession session = threadLocal.get();
        if(session != null){
            session.close();
            threadLocal.set(null);
        }
    }
}
